package com.ezjie.ielts.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.http.message.BasicNameValuePair;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.ezjie.ielts.model.AnswerInfo;

/**
 * 字符的工具类
 * 
 * @author renyangyang
 * 
 */
public class StringUtil {

	/**
	 * 判断字符是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return (str == null || str.length() == 0);
	}

	/**
	 * 转化个位数为2位字符数 1---->01
	 * 
	 * @param i
	 * @return
	 */
	public static String addZreoIfLessThanTen(int i) {

		String string = "";
		int ballNum = i;
		if (ballNum < 10) {
			string = "0" + ballNum;
		} else {
			string = ballNum + "";
		}
		return string;
	}

	public static int getTotal(HashMap<Integer, Boolean> map) {
		int i = 0;
		for (Map.Entry<Integer, Boolean> entry : map.entrySet()) {
			if (entry.getValue()) {
				i++;
			}
		}
		return i;
	}

	/**
	 * 是否为Intger类型的
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 通过路径或者url获得 文件名字 xx/test.txt--> test.txt
	 * 
	 * @param path
	 * @return
	 */
	public static String getFilename(String path) {
		if (path == null) {
			return null;
		}
		int separatorIndex = path.lastIndexOf("/");
		return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
	}

	/**
	 * 去除字符中的所有空格
	 * 
	 * @param string
	 * @return
	 */
	public static String trimAllWhitespace(String string) {
		if (null == string || "".equals(string)) {
			return "";
		}
		return string.replace(" ", "");
	}

	/**
	 * encode字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String utf8Encode(String str) {
		if (!isEmpty(str) && str.getBytes().length != str.length()) {
			try {
				return URLEncoder.encode(str, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
			}
		}
		return str;
	}

	/**
	 * 打印 上传的参数
	 * 
	 * @param formparams
	 * @return
	 */
	public static String printParams(List<BasicNameValuePair> formparams) {
		StringBuffer sbBuffer = new StringBuffer();
		for (int i = 0; i < formparams.size(); i++) {
			if (i == 0) {
				sbBuffer.append("?" + formparams.get(i).getName() + "=" + formparams.get(i).getValue());
			} else {
				sbBuffer.append("&" + formparams.get(i).getName() + "=" + formparams.get(i).getValue());
			}
		}
		return sbBuffer.toString();
	}

	public static final String EMPTY = "";

	public static <T> String join(final T... elements) {
		return join(elements, null);
	}

	public static String join(final Object[] array, final String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, 0, array.length);
	}

	public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = EMPTY;
		}

		// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) +
		// len(separator))
		// (Assuming that all Strings are roughly equally long)
		final int noOfItems = endIndex - startIndex;
		if (noOfItems <= 0) {
			return EMPTY;
		}

		final StringBuilder buf = new StringBuilder(noOfItems * 16);

		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(array[i]);
			}
		}
		return buf.toString();
	}

	/**
	 * 从输出流转成字符
	 * 
	 * @param is
	 * @return
	 */
	public static String readStream(InputStream is) {
		ByteArrayOutputStream bo = null;
		try {
			bo = new ByteArrayOutputStream();
			int i = is.read();
			while (i != -1) {
				bo.write(i);
				i = is.read();
			}
			return bo.toString();
		} catch (IOException e) {
			LogUtils.exception(e);
		} finally {
			try {
				if (bo != null) {
					bo.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				LogUtils.exception(e);
			}
		}
		return "";
	}

	public static String generateTime(long time) {
		int totalSeconds = (int) (time / 1000);
		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;

		return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d",
				minutes, seconds);
	}

	/**
	 * 对阅读原文数据分割
	 * 
	 * @param origin
	 * @return
	 */
	public static List<String> splitOriginStr(String origin) {
		List<String> list = new ArrayList<String>();
		if (null == origin) {
			origin = "";
		}

		String[] array = origin.split("\r\n");
		for (String str : array) {
			if (str.length() > 0) {
				list.add(str);
			}
		}

		return list;
	}

	/**
	 * 遍历正确答案
	 * 
	 * @param answer
	 * @return
	 */
	public static List<String> getRightAnswerList(String answer) {
		List<String> list = new ArrayList<String>();
		JSONArray array = JSONArray.parseArray(answer);

		for (int i = 0; i < array.size(); i++) {
			AnswerInfo answerInfo = array.getObject(i, AnswerInfo.class);

			if (Boolean.valueOf(answerInfo.is_right)) {
				list.add(answerInfo.text);
			}

		}

		return list;
	}

	/**
	 * 遍历正确答案 --是非题
	 * 
	 * @param answer
	 * @return
	 */
	public static List<String> getRightAnswerListByTrueOrFlase(String answer) {
		List<String> list = new ArrayList<String>();
		JSONArray array = JSONArray.parseArray(answer);

		for (int i = 0; i < array.size(); i++) {
			AnswerInfo answerInfo = array.getObject(i, AnswerInfo.class);

			if (Boolean.valueOf(answerInfo.is_right)) {
				list.add(answerInfo.text);
			}

		}

		return list;
	}

	/**
	 * 答案解析页 展示用
	 * 
	 * @param list
	 * @return
	 */
	public static String getAnswerStr(List<String> list) {
		StringBuilder builder = new StringBuilder();

		for (int i = 0; i < list.size(); i++) {
			builder.append(list.get(i));
			if (i < list.size() - 1) {
				builder.append("\r\n");
			}
		}

		return builder.toString();
	}

	public static boolean checkPassword(String pwd) {
		if (TextUtils.isEmpty(pwd))
			return false;
		if (pwd.length() > 16 || pwd.length() < 6)
			return false;
		return true;
	}

	/**
	 * 弹框 单列表答案
	 * 
	 * @param answer
	 * @return
	 */
	public static ArrayList<KeyValuePair<String, Boolean>> getAnswers(String answer) {
		ArrayList<KeyValuePair<String, Boolean>> list = new ArrayList<KeyValuePair<String, Boolean>>();
		JSONArray array = JSONArray.parseArray(answer);

		for (int i = 0; i < array.size(); i++) {
			AnswerInfo answerInfo = array.getObject(i, AnswerInfo.class);
			KeyValuePair<String, Boolean> value = new KeyValuePair<String, Boolean>(answerInfo.text,
					Boolean.valueOf(answerInfo.is_right));
			list.add(value);
		}

		return list;
	}

	/**
	 * 忽略大小写
	 * 
	 * @param list
	 * @param str
	 * @return
	 */
	public static boolean contains(List<String> list, String str) {
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).toLowerCase().equals(str.toLowerCase())) {
				return true;
			}
		}

		return false;

	}

	/**
	 * 去掉答案的选项号
	 * 
	 * @param answer
	 * @return
	 */
	public static String deleteNo(String answer) {
		if (answer.length() > 2) {
			int index = answer.indexOf(".");

			if (index != -1 && index <= 5) {
				String substr = answer.substring(0, index);

				for (int i = 0; i < substr.length(); i++) {
					if (Character.isLowerCase(substr.charAt(i))) {
						return answer;
					}
				}

				return answer.substring(index + 1, answer.length());
			}
		}

		return answer;
	}

	public static String queryFileName(String filestr) {
		String fileName;
		// 查找 文件名
		try {
			int lastIndexOf = filestr.lastIndexOf("/");
			fileName = filestr.substring(lastIndexOf + 1);
		} catch (Exception e) {
			// e.printStackTrace();
			LogUtils.e("queryFileName is error");
			fileName = "";
		}
		return fileName;
	}

	/**
	 * 首字母大写，之后小写
	 * 
	 * @param str
	 * @return
	 */
	public static String captureName(String str) {

		char[] cs = str.toCharArray();

		for (int i = 0; i < cs.length; i++) {
			if (i == 0 || (i > 0 && cs[i - 1] == ' ')) {
				cs[i] = String.valueOf(cs[i]).toUpperCase().charAt(0);
			} else {
				cs[i] = String.valueOf(cs[i]).toLowerCase().charAt(0);
			}
		}

		return String.valueOf(cs);
	}

	/**
	 * 分隔多选题答案
	 * 
	 * @param answer
	 * @return
	 */
	public static List<String> getAnswerList(String answer) {
		List<String> list = new ArrayList<String>();

		String regEx = "\r\n";
		Pattern p = Pattern.compile(regEx);
		String[] strss = p.split(answer);
		for (String str : strss) {
			list.add(str);
		}

		return list;
	}

}
